package com.whcoding.test.controller;


import com.whcoding.test.pojo.UserTestVO;
import com.whcoding.test.pojo.ValidationParamVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;

/**
 * @program: spring-boot-learning
 * @description: 参数检测
 * - 对于`@PathVariable`和`@RequestParam`，在controller上加`@Validated`注解，在参数上做验证
 * - 对于`@RequestBody`，在变量前面加`@Validated`，在类属性里面做验证
 * - 验证多个参数的情况应该不会用到，拦截`BindException` 异常
 * @author: whcoding
 * @create: 2022-08-01 10:44
 **/
@RequestMapping("validation")
@RestController
@Validated
public class ValidationController {

	private static final Logger logger = LoggerFactory.getLogger(ValidationController.class);

	//参数检测方法一：

	/**
	 * 参数检查:第一版本
	 *
	 * @param userName
	 * @return
	 */
	@GetMapping("checkParam")
	public ResponseEntity checkParam(@RequestParam String userName, Integer userCode) {

		if (StringUtils.isEmpty(userName)) {
			throw new RuntimeException("userName参数不能为空");
		}
		if (userCode.equals(0)) {
			throw new RuntimeException("userCode参数必须大于0");
		}
		logger.info("checkParam  do something");
		System.out.println("checkParam");
		//do something
		return ResponseEntity.ok().build();
	}

	/**
	 * 参数检查:第2版本
	 *
	 * @param userName
	 * @return
	 */
	@GetMapping("checkParam2")
	public ResponseEntity checkParam2(@Validated @NotBlank(message = "用户名称不能为空") String userName) {
		//do something
		logger.info("checkParam2  do something");
		System.out.println("获取到的userName"+userName);
		System.out.println("checkParam2");
		return ResponseEntity.ok().build();
	}


	/**
	 * 参数检查:第3版本
	 *
	 * @param paramVO
	 * @return
	 */
	@PostMapping("checkParam3")
	public ResponseEntity checkParam3(@Validated @RequestBody ValidationParamVO paramVO) {
		//do something
		logger.info("checkParam3  do something");
		System.out.println("checkParam3");
		return ResponseEntity.ok().build();
	}

	/**
	 * Assert 验证参数
	 * @param idStr
	 */
	@GetMapping("checkID")
	public void checkID(String idStr){
		System.out.println("开始执行方法checkID");
		Assert.hasLength(idStr, "ID不能为空");
		System.out.println("结束执行方法checkID");
	}

	/**
	 * 验证多个参数
 	 */
	@PostMapping("/checkMoreVO")
	public String checkMoreVO(@Validated ValidationParamVO paramVO, @Validated UserTestVO userVO) {
		return "do something ...";
	}

}
